package edu.indiana.d2i.ontology.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AccessDBUtil {
	private String url = "jdbc:odbc:";
	private String username = "";
	private String password = "";
	
	private Connection conn = null;
	private PreparedStatement prepStatement = null;
	private ResultSet resultSet = null;
	
	public AccessDBUtil(String datasource, String usr, String pwd) {
		url += datasource;
		username = usr;
		password = pwd;
	}
	
	public void openConnection() {
		try {
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			conn = DriverManager.getConnection(url, username, password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void closeConnection() {
		try {
			if (conn != null) conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public ResultSet query(String sql) {	
		try {
			if (resultSet != null)
				resultSet.close();
			if (prepStatement != null)
				prepStatement.close();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		
		if (conn != null) {
			try {
				prepStatement = conn.prepareStatement(sql);
				resultSet = prepStatement.executeQuery();
//				prepStatement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return resultSet;
	}
}
